﻿using CoreShop.Library.Units;
using CoreShop.Model.FromBody;
using CoreShop.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static CoreShop.Services.PosRemoteServices;
using CoreShop.Services;
using CoreShop.Library;
using Sunny.UI.Win32;
using FastMember;
using NPOI.SS.Formula.Functions;
using Sunny.UI;
using Newtonsoft.Json;
using SqlSugar.Extensions;
using static System.Windows.Forms.AxHost;
using CoreShop.Model.UI;
using Yitter.IdGenerator;
using static System.Runtime.CompilerServices.RuntimeHelpers;
using System.Security.Cryptography;
using Model.ProductModel;
using Newtonsoft.Json.Linq;
using System.Windows.Forms;
using System.Threading;

namespace CoreShop.App.Units.Interface
{
    public class FoodApiUtil
    {
        private static readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1); // 初始1个名额，最大1个

        public static async Task<string> DoWorkAsync()
        {
            await Task.Delay(10000);
            return "异步完成。";
        }

        /// <summary>
        /// 生成商品条码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static async Task<ReturnModel> GetProductItemCode(sysuser sysuser)
        {
            JObject keyValues = new JObject();
            keyValues.Add(new JProperty("itemSortCode", ""));
            //return HttpHelper.PostSendMessage(baseUrl, $"{SERVER.Product}{API.Product_Generate}", keyValues.ToString(), 60, "", sysuser);
            var returnModel = await HttpHelperAsync.PostDataAsync(ApiConsVars.baseUrl, $"{SERVER.Product}{API.Product_Generate}", keyValues.ToString(), 60, "", AppConstVars.sysUser);
            return returnModel;
        }


        /// <summary>
        /// 同步数据线程
        /// </summary>
        /// <param name="type"></param>
        public static async Task<AsyncReturnModel> LoadGoodDataAsync(long spuId)
        {
            var exchange = new corecmsexchangeServices().GetDataById(AppConstVars.sysUser.storeId);
            AsyncReturnModel asyncReturnModel = new AsyncReturnModel();
            var goodsResult = await GetGoodDataList(AppConstVars.sysStore, AppConstVars.sysUser, exchange, spuId);
            return asyncReturnModel;
        }

        /// <summary>
        /// 改价格表单价
        /// </summary>
        public static async Task<AsyncReturnModel> UpdateBranchPrice(BranchPriceDto keyValues, sysuser sysuser)
        {
            AsyncReturnModel asyncReturnModel = new AsyncReturnModel();
            try
            {
                string keyStr = keyValues.ToJsonString();
                //ReturnModel returnModel = HttpHelper.PostSendMessage(baseUrl, $"{SERVER.Product}{API.BranchPriceUpdate}", keyStr, 60, "", sysuser);
                var returnModel = await HttpHelperAsync.PostDataAsync(ApiConsVars.baseUrl, $"{SERVER.Product}{API.BranchPriceUpdate}", keyStr, 60, "", AppConstVars.sysUser);
                BaseReturnModel baseReturn = returnModel.MessageOrString.JsonToEntity<BaseReturnModel>();

                if (baseReturn.code != 200 || baseReturn.data == null)
                {
                    asyncReturnModel.msg = $"保存数据出错:{baseReturn.msg}";
                    return asyncReturnModel;
                }
                asyncReturnModel.status = CommFunc.ConvertToBooten(baseReturn.data);
                asyncReturnModel.msg = baseReturn.msg;
            }
            catch (Exception ex) { asyncReturnModel.msg = ex.Message; }
            return asyncReturnModel;
        }


        /// <summary>
        /// 今日调价（生成调价单)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static async Task<AsyncReturnModel> ChgPriceHeadByPos(GsPdtChgPriceModel gsPdtChgPriceModel, sysuser sysuser)
        {
            AsyncReturnModel asyncReturnModel = new AsyncReturnModel();
            //ReturnModel result = HttpHelper.PostSendMessage(baseUrl, $"{SERVER.Product}{API.ChgPriceHeadByPos}", gsPdtChgPriceModel.ToJsonString(), 60, "", sysuser);
            var result = await HttpHelperAsync.PostDataAsync(ApiConsVars.baseUrl, $"{SERVER.Product}{API.ChgPriceHeadByPos}", gsPdtChgPriceModel.ToJsonString(), 60, "", AppConstVars.sysUser);
            if (result.Status != ReturnStatus.Success)
            {
                asyncReturnModel.msg = $"今日调价失败:{result.MessageOrString}";
                return asyncReturnModel;
            }

            ApiReturnModel apiReturnModel = result.MessageOrString.JsonToEntity<ApiReturnModel>();

            if (apiReturnModel.code != 200)
            {
                asyncReturnModel.msg = $"今日调价失败:{apiReturnModel.msg}";
                return asyncReturnModel;
            }

            if (apiReturnModel.data == null)
            {
                asyncReturnModel.msg = $"今日调价失败:{apiReturnModel.msg}";
                return asyncReturnModel;
            }

            var dataList = JsonConvert.DeserializeObject<List<corecmschgprice>>(apiReturnModel.data.ToString());
            if (dataList.Count > 0)
            {
                var returnValue = new corecmschgpriceServices().InsertOrUpdate(dataList);                
                if (returnValue) asyncReturnModel.total = dataList.Count;
            }
            asyncReturnModel.status = true;
            return asyncReturnModel;
        }


        /// <summary>
        /// 改商品单价
        /// </summary>
        public static async Task<AsyncReturnModel> UpdateSpuPrice(SpuSpecUpdateDto keyValues, sysuser sysuser)
        {
            AsyncReturnModel asyncReturnModel = new AsyncReturnModel();
            try
            {
                var returnModel = await HttpHelperAsync.PostDataAsync(ApiConsVars.baseUrl, $"{SERVER.Product}{API.SpuSaPriceUpdate}", keyValues.ToJsonString(), 60, "", AppConstVars.sysUser);

                BaseReturnModel baseReturn = returnModel.MessageOrString.JsonToEntity<BaseReturnModel>();

                if (baseReturn.code != 200 || baseReturn.data == null)
                {
                    asyncReturnModel.msg = $"保存数据出错:{baseReturn.msg}";
                    return asyncReturnModel;
                }
                asyncReturnModel.msg = baseReturn.msg;
                asyncReturnModel.status = CommFunc.ConvertToBooten(baseReturn.data);                
            }
            catch (Exception ex) 
            {
                asyncReturnModel.msg = ex.Message;            
            }
            return asyncReturnModel;
        }


        #region 商品调价单
        /// <summary>
        /// 商品调价单
        /// </summary>
        /// <param name="sWebUrl"></param>
        /// <param name="ht"></param>
        /// <param name="jToken"></param>
        /// <returns></returns>
        public static async Task<AsyncReturnModel> GetGoodChgPriceList(corecmsstore store, sysuser user, corecmsexchange exchange)
        {
            AsyncReturnModel asyncReturnModel = new AsyncReturnModel();
            List<corecmschgprice> dataList = new List<corecmschgprice>();
            try
            {
                var sysDataPost = new SysDataPost();
                sysDataPost.startTime = CommFunc.ConvertDateTimeToString(exchange.chgPriceTime);
                sysDataPost.branchId = store.branchId.ToString();
                string postStr = JsonConvert.SerializeObject(sysDataPost);
                var result = await HttpHelperAsync.PostDataAsync(ApiConsVars.baseUrl, $"{SERVER.Product}{API.GetChgpriceList}", postStr, 60, "", AppConstVars.sysUser);
                if (result == null || string.IsNullOrEmpty(result.MessageOrString))
                {
                    return asyncReturnModel;
                }
                ApiReturnModel apiReturnModel = result.MessageOrString.JsonToEntity<ApiReturnModel>();
                dataList = JsonConvert.DeserializeObject<List<corecmschgprice>>(apiReturnModel.data.ToString());
                if (dataList.Count > 0)
                {
                    var returnValue = new corecmschgpriceServices().InsertOrUpdate(dataList);
                    DateTime updateTime = dataList.Select(p => p.updateTime.ObjToDate()).Max();

                    exchange.chgPriceId = dataList.Select(p => p.chgpriceLineId).Max();
                    exchange.chgPriceTime = updateTime;
                    new corecmsexchangeServices().UpdateAsync(new corecmsexchange { storeId = store.id, chgPriceId = exchange.chgPriceId, chgPriceTime = exchange.chgPriceTime });
                }
                asyncReturnModel.total = dataList.Count;                
            }
            catch (Exception ex)
            {
                asyncReturnModel.msg = ex.Message;
                exchange.status = false;
                await new corecmsprinttasklogServices().InsertAsync(ex.Message);
                if (dataList.Count > 0) await SaveGoodsPrice(dataList);
                return asyncReturnModel;
            }
            return asyncReturnModel;
        }

        /// <summary>
        /// 保存单个商品
        /// </summary>
        /// <param name="foodList"></param>
        /// <param name="specList"></param>
        /// <param name="msg"></param>
        public static async Task<bool> SaveGoodsPrice(List<corecmschgprice> dataList)
        {
            bool result = true;
            var priceSrv = new corecmschgpriceServices();
            foreach (corecmschgprice price in dataList)
            {
                try
                {
                   await priceSrv.InsertOrUpdateAsync(price);
                }
                catch (Exception ex)
                {
                    result = false;
                    string priceMsg = JsonConvert.SerializeObject(price);
                    await new corecmsprinttasklogServices().InsertAsync(priceMsg);
                    await new corecmsprinttasklogServices().InsertAsync(ex.Message);
                }
            }
            return result;
        }

        #endregion

        /// <summary>
        /// 获取商品库商品
        /// </summary>
        public static async Task<ProductPdtStandderSpuInfo> GetPdtStanderSpuInfo(GsAddProductPdtInfoModel PostInfo)
        {
            try
            {
                string postPara = PostInfo.ToJsonString();
                var result = await HttpHelperAsync.PostDataAsync(ApiConsVars.baseUrl, $"{SERVER.Product}{API.GetPdtStanderSpuInfo}", postPara, 60, "", AppConstVars.sysUser);
                if (result == null || string.IsNullOrEmpty(result.MessageOrString))
                {
                    return null;
                }
                ApiReturnModel apiReturnModel = result.MessageOrString.JsonToEntity<ApiReturnModel>();
                if (apiReturnModel != null && apiReturnModel.data != null && (apiReturnModel.code == 200))
                {
                    ProductPdtStandderSpuInfo ReturnModel = apiReturnModel.data.ToString().JsonToEntity<List<ProductPdtStandderSpuInfo>>().Find(s => s.spuBarcode == PostInfo.spuBarcode);
                    if (ReturnModel != null) return ReturnModel;
                }
            }
            catch (Exception ex)
            {
            }
            return null;
        }


        public static async Task<ApiReturnModel> GetItemSortCode(long parentId)
        {
            string para = $"{SERVER.Product}{API.GetItemSortCode}/{parentId}";
            ReturnModel returnModel = await HttpHelperAsync.GetDataAsync(ApiConsVars.baseUrl, para, 60, AppConstVars.sysUser);

            if (returnModel.Status != ReturnStatus.Success)
            {
                UIMessageBox.Show($"兑换错误,{returnModel.MessageOrString}");
                return null;
            }

            ApiReturnModel InfoReturn = returnModel.MessageOrString.JsonToEntity<ApiReturnModel>();
            if (InfoReturn == null || InfoReturn.code != 200)
            {
                UIMessageBox.Show($"兑换错误,{InfoReturn.msg}");
                return InfoReturn;
            }
            return InfoReturn;
        }

        /// <summary>
        /// 保存商品分类
        /// </summary>
        public static async Task<AsyncReturnModel> SaveProductType(InsertPdtItemSortModel PostInfo)
        {
            AsyncReturnModel asyncReturnModel = new AsyncReturnModel();
            try
            {
                string postPara = PostInfo.ToJsonString();
                var result = await HttpHelperAsync.PostDataAsync(ApiConsVars.baseUrl, $"{SERVER.Product}{API.InsertPdtItemSort}", postPara, 60, "", AppConstVars.sysUser);
                if (result == null || string.IsNullOrEmpty(result.MessageOrString))
                {
                    return asyncReturnModel;
                }
                ApiReturnModel apiReturnModel = result.MessageOrString.JsonToEntity<ApiReturnModel>();
                if (apiReturnModel != null && apiReturnModel.data != null && (apiReturnModel.code == 200))
                {
                    List<GsSordItemClassModel> dataList = new List<GsSordItemClassModel>();
                    GsSordItemClassModel dataModel = JsonConvert.DeserializeObject<GsSordItemClassModel>(CommFunc.ConvertToString(apiReturnModel.data));
                    if (dataModel != null)
                    {
                        dataList.Add(dataModel);
                        List<corecmsfoodcategory> foodCategoryList = new List<corecmsfoodcategory>();
                        foodCategoryList.AddRange(ModelHelper.GoodsCategoryToFoodCateory(dataList, AppConstVars.sysStore));
                        var returnValue = new corecmsfoodcategoryServices().InsertOrUpdate(foodCategoryList);
                    }
                    asyncReturnModel.msg = "新增成功！";
                    asyncReturnModel.status = true;
                    return asyncReturnModel;
                }
                asyncReturnModel.msg = apiReturnModel.msg;
            }
            catch (Exception ex)
            {
                asyncReturnModel.msg = ex.Message;
            }
            return asyncReturnModel;
        }


        /// <summary>
        /// 保存商品资料public static async Task<string> DoWorkAsync()
        /// </summary>
        public static async Task<AsyncGoodsListModel> SaveGoodsInfo(GsAddProductPdtInfoModel PostInfo)
        {
            AsyncGoodsListModel result = new AsyncGoodsListModel();
            try
            {
                var returnModel = await HttpHelperAsync.PostDataAsync(ApiConsVars.baseUrl, $"{SERVER.Product}{SERVER.Product}{API.AddSaveForPos}", PostInfo.ToJsonString(), 60, "", AppConstVars.sysUser);

                //var result = new PosRemoteServices().SaveProductInfo(PostInfo,AppConstVars.sysUser);
                if (result == null || string.IsNullOrEmpty(returnModel.MessageOrString))
                {
                    return result;
                }
                ApiReturnModel apiReturnModel = returnModel.MessageOrString.JsonToEntity<ApiReturnModel>();
                if (apiReturnModel != null && apiReturnModel.data != null && (apiReturnModel.code == 200))
                {
                    GsProducInfoModel gsProducInfo = JsonConvert.DeserializeObject<GsProducInfoModel>(apiReturnModel.data.ToString());
                    result = await SaveGoodsList(gsProducInfo, AppConstVars.sysStore);

                    result.msg = "新增成功！";
                    result.status = true;
                    return result;
                }
                result.msg = apiReturnModel.msg;
                return result;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                return result;
            }
        }

        /// <summary>
        /// 商品（新版本2.0接口）
        /// </summary>
        /// <param name="sWebUrl"></param>
        /// <param name="ht"></param>
        /// <param name="jToken"></param>
        /// <returns></returns>
        public static async Task<AsyncGoodsListModel> GetGoodDataList(corecmsstore store, sysuser user, corecmsexchange exchange, long spuId = 0)
        {
            AsyncGoodsListModel result = new AsyncGoodsListModel();
            // 尝试获取信号量，如果已被占用则直接返回（不等待）,Wait(0) 表示立即返回，不阻塞
            if (!_semaphore.Wait(0))
            {
                result.msg = "商品同步下载中，请不要频繁提交。";
                return result;
            }
            try
            {
                var url = string.Concat(ApiConsVars.baseUrl, $"{SERVER.Product}{API.GetPdtSpuBranch}");

                var sysDataPost = new SysGoodsPost();                
                sysDataPost.branchId = store.branchId.ToString();
                if (spuId > 0)
                    sysDataPost.spuId = spuId.ToString();
                else
                    sysDataPost.startTime = CommFunc.ConvertDateTimeToString(exchange.foodTime);

                string postStr = JsonConvert.SerializeObject(sysDataPost);
                string retStr = Library.HttpHelper.httpPost(url, postStr, user.ccessToken);
                AdminUiCallBack res = JsonConvert.DeserializeObject<AdminUiCallBack>(retStr);
                if ((res != null) && (res.code == 401))
                {
                    await SystemApiUtil.RefreshTokenAsync(AppConstVars.sysStore, AppConstVars.sysUser);
                    return result;
                }
                var spuJson = BrotliDecompressor.Decompress(res.data.ToString(), Encoding.UTF8);
                GsProducInfoModel gsProducInfo = JsonConvert.DeserializeObject<GsProducInfoModel>(spuJson);
                result = await SaveGoodsList(gsProducInfo, store);                
                if (result.foodList != null && result.foodList.Count > 0)
                    exchange.foodId = result.foodList.Select(p => p.id).Max();
                exchange.foodTime = CommFunc.ConvertToDateTime(gsProducInfo.syncTime);

                //单个商品同步时，不更新corecmsexchange
                if (spuId <= 0)                                    
                    new corecmsexchangeServices().UpdateAsync(new corecmsexchange { storeId = store.id, foodId = exchange.foodId, foodTime = exchange.foodTime });
  
                return result;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                exchange.status = false;
                return result;
            }
            finally
            {
                _semaphore.Release(); // 释放信号量，允许下次调用
            }
        }

        /// <summary>
        /// 商品（新版本2.0接口）
        /// </summary>
        /// <param name="sWebUrl"></param>
        /// <param name="ht"></param>
        /// <param name="jToken"></param>
        /// <returns></returns>
        public static async Task<AsyncGoodsListModel> SaveGoodsList(GsProducInfoModel gsProducInfo, corecmsstore store)
        {
            AsyncGoodsListModel result = new AsyncGoodsListModel();
            List<corecmsfood> foodList = new List<corecmsfood>();
            List<corecmsfoodspec> specList = new List<corecmsfoodspec>();
            bool returnValue = false;
            try
            {
                if (gsProducInfo == null) return result;
                if ((gsProducInfo.spuBranchList == null) && (gsProducInfo.spuBranchSpecList == null)
                && (gsProducInfo.spuBranchBarList == null) && (gsProducInfo.spuParentList == null)
                && (gsProducInfo.spuParentSpecList == null) && (gsProducInfo.spuTenanBarList == null)
                && (gsProducInfo.spuTenanPriceList == null)) return result;

                List<corecmsfoodbarcodes> foodBarcodes = new List<corecmsfoodbarcodes>();

                //本商户的商品及规格
                if (gsProducInfo.spuBranchList != null && gsProducInfo.spuBranchList.Count > 0
                    && gsProducInfo.spuBranchSpecList != null && gsProducInfo.spuBranchSpecList.Count > 0)
                {
                    foreach (var gsSpuInfo in gsProducInfo.spuBranchList)
                    {
                        List<corecmsfoodspec> foodSpecList = new List<corecmsfoodspec>();
                        var spuSpecList = gsProducInfo.spuBranchSpecList.Where(p => p.spuId == gsSpuInfo.spuId).ToList();
                        if (spuSpecList.Count > 0)
                        {
                            GsSpuSpecModel spuSpecDefault = spuSpecList.FirstOrDefault();//默认规格
                            foreach (var gsSpuSpec in spuSpecList)
                            {
                                if (CommFunc.ConvertToInt32(gsSpuSpec.canDefault) == 0) spuSpecDefault = gsSpuSpec;
                                foodSpecList.Add(ModelHelper.GsSpuToFoodSpec(gsSpuInfo, gsSpuSpec, store));
                            }
                            if (spuSpecDefault != null && foodSpecList != null && foodSpecList.Count > 0)
                            {
                                foodList.Add(ModelHelper.GsSpuToFood(gsSpuInfo, spuSpecDefault, store, store.corpId));
                                specList.AddRange(foodSpecList);
                            }
                        }
                    }
                }

                if (gsProducInfo.spuBranchBarList != null && gsProducInfo.spuBranchBarList.Count > 0)
                    foodBarcodes.AddRange(gsProducInfo.spuBranchBarList);

                //总商户的商品及规格
                if (gsProducInfo.spuParentList != null && gsProducInfo.spuParentList.Count > 0
                    && gsProducInfo.spuParentSpecList != null && gsProducInfo.spuParentSpecList.Count > 0)
                {
                    foreach (var gsSpuInfo in gsProducInfo.spuParentList)
                    {
                        List<corecmsfoodspec> foodSpecList = new List<corecmsfoodspec>();

                        var spuSpecList = gsProducInfo.spuParentSpecList.Where(p => p.spuId == gsSpuInfo.spuId).ToList();
                        if (spuSpecList.Count > 0)
                        {
                            GsSpuSpecModel spuSpecDefault = spuSpecList.FirstOrDefault();
                            foreach (var gsSpuSpec in spuSpecList)
                            {
                                if (CommFunc.ConvertToInt32(gsSpuSpec.canDefault) == 0) spuSpecDefault = gsSpuSpec;
                                foodSpecList.Add(ModelHelper.GsSpuToFoodSpec(gsSpuInfo, gsSpuSpec, store));
                            }
                            if (spuSpecDefault != null && foodSpecList != null && foodSpecList.Count > 0)
                            {
                                foodList.Add(ModelHelper.GsSpuToFood(gsSpuInfo, spuSpecDefault, store, store.parentTenantId));
                                specList.AddRange(foodSpecList);
                            }
                        }
                    }
                }
                if (gsProducInfo.spuTenanBarList != null && gsProducInfo.spuTenanBarList.Count > 0)
                    foodBarcodes.AddRange(gsProducInfo.spuTenanBarList);
                try
                {
                    returnValue = new corecmsfoodServices().InsertOrUpdate(foodList);
                    returnValue = new corecmsfoodspecServices().InsertOrUpdate(specList);
                }
                catch (Exception ex)
                {
                    result.msg = ex.Message;
                    returnValue = false;
                }

                //批量更新失败时，转为单个更新。
                if (returnValue == false)
                {
                    var saveResult = await SaveGoodsData(foodList, specList);
                    result.msg = saveResult.msg;
                }

                #region 根据价格表更新商品规格表
                if (gsProducInfo.spuTenanPriceList != null && gsProducInfo.spuTenanPriceList.Count > 0)
                {
                    long batchId = YitIdHelper.NextId();
                    foreach (var priceItem in gsProducInfo.spuTenanPriceList)
                    {
                        priceItem.batchId = batchId;
                        priceItem.stopSaleFlag = priceItem.stopSaleFlag == true;
                    }
                    new corecmsfoodpriceServices().InsertOrUpdate(gsProducInfo.spuTenanPriceList);
                    string msql = @"UPDATE corecmsfoodspec e JOIN corecmsfoodprice p ON e.id = p.pdtSpuSpecId
                            SET e.onLine = p.stopSaleFlag,e.posPrice = p.saPrice,e.vipPrice = p.vipPrice,e.vvipPrice = p.vvipPrice
                            where p.batchID = {0} and p.saPrice > 0 and p.specTenantId <> p.tenantId and p.tenantId = {1};
                            UPDATE corecmsfoodspec e JOIN corecmsfoodprice p ON e.id = p.pdtSpuSpecId
                            SET e.onLine = p.stopSaleFlag,e.posPrice = p.specSaPrice,e.vipPrice = p.specVipPrice,e.vvipPrice = p.specVvipPrice
                            where p.batchID = {0} and p.saPrice = 0 and p.specTenantId <> p.tenantId and p.tenantId = {1};";
                    msql = string.Format(msql, batchId, store.corpId);
                    try
                    {
                        var db = new corecmsfoodspecServices().GetInstance();
                        db.Ado.ExecuteCommand(msql);
                    }
                    catch { }
                }
                #endregion

                //一品多码
                if (foodBarcodes.Count > 0)
                    new corecmsfoodbarcodesServices().InsertOrUpdate(foodBarcodes);

                result.count = foodList.Count;
                result.foodList = foodList;
                return result;
            }
            catch (Exception ex)
            {
                result.msg = ex.Message;
                result.status = false;
                return result;
            }
        }

        /// <summary>
        /// 保存单个商品
        /// </summary>
        /// <param name="foodList"></param>
        /// <param name="specList"></param>
        /// <param name="msg"></param>
        public static async Task<AsyncReturnModel> SaveGoodsData(List<corecmsfood> foodList, List<corecmsfoodspec> specList)
        {
            AsyncReturnModel returnModel = new AsyncReturnModel();
            returnModel.status = true;
            var foodSrv = new corecmsfoodServices();
            foreach (corecmsfood food in foodList)
            {
                try
                {
                    await foodSrv.InsertOrUpdateAsync(food);
                }
                catch (Exception ex)
                {
                    returnModel.status = false;
                    string foodMsg = JsonConvert.SerializeObject(food);
                    await new corecmsprinttasklogServices().InsertAsync($"商品<{food.number}下载失败.");
                    await new corecmsprinttasklogServices().InsertAsync(foodMsg);
                    await new corecmsprinttasklogServices().InsertAsync(ex.Message);
                    returnModel.msg = returnModel.msg + ";" + ex.Message;
                }
            }
            var specSrv = new corecmsfoodspecServices();
            foreach (corecmsfoodspec spec in specList)
            {
                try
                {
                    specSrv.InsertOrUpdate(spec);
                }
                catch (Exception ex)
                {
                    returnModel.status = false;
                    string specMsg = JsonConvert.SerializeObject(spec);
                    await new corecmsprinttasklogServices().InsertAsync($"商品<{spec.number}下载失败.");
                    await new corecmsprinttasklogServices().InsertAsync(specMsg);
                    await new corecmsprinttasklogServices().InsertAsync(ex.Message);
                    returnModel.msg = returnModel.msg + ";" + ex.Message;
                }
            }
            //return result;
            return returnModel;
        }

    }
}
